package com.android.fragmentdemo.defineviews

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.get
import com.android.fragmentdemo.R

class ListDataViewGroup @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : ViewGroup(context, attributeSet) {


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        var mWidth = 0
        var mHeight = 0
        for (i in 0.until(childCount)) {
            val child = get(i)
            Log.d(TAG,"$TAG --- ${child is ExpandViewGroup}")
            //child.measure(widthMeasureSpec, heightMeasureSpec)
            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0)
            mWidth += child.measuredWidth
            mHeight += child.measuredHeight
            Log.d(TAG, "$TAG --- mWidth:${mWidth},mHeight:${mHeight}")
        }

        setMeasuredDimension(
            MeasureSpec.makeMeasureSpec(mWidth, MeasureSpec.EXACTLY) - paddingStart - paddingEnd,
            MeasureSpec.makeMeasureSpec(mHeight, MeasureSpec.EXACTLY) - paddingTop - paddingBottom
        )
    }

    override fun onLayout(force: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        for (i in 0.until(childCount)) {
            val child = get(i)
            val childWidth = child.measuredWidth
            val childHeight = child.measuredHeight
            child.layout(0, 0, childWidth, childHeight)
        }
    }

    override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams {
        return LayoutParams(context, attrs)
    }

    companion object {
        const val TAG = "ListDataViewGroup"
    }
}